/**
 * 格式化时间
 * @param {Date|string|number} time - 可以是 Date 对象、时间戳字符串或数字
 * @param {string} format - 格式模板，默认 'YYYY-MM-DD hh:mm'
 * @returns {string} 格式化后的时间字符串
 */
export function formatTime(time, format = 'YYYY-MM-DD hh:mm') {
	if (!time) return ''

	let date
	if (time instanceof Date) {
		date = time
	} else {
		// 处理微信云数据库的 serverDate 对象
		if (typeof time === 'object' && time.$date) {
			date = new Date(time.$date)
		} else {
			// 处理时间戳（可能是字符串或数字）
			date = new Date(typeof time === 'string' ? parseInt(time) : time)
		}
	}

	// 如果转换失败，返回空字符串
	if (isNaN(date.getTime())) return ''

	const padZero = (num) => (num < 10 ? `0${num}` : num)

	const year = date.getFullYear()
	const month = padZero(date.getMonth() + 1)
	const day = padZero(date.getDate())
	const hour = padZero(date.getHours())
	const minute = padZero(date.getMinutes())
	const second = padZero(date.getSeconds())

	return format
		.replace('YYYY', year)
		.replace('MM', month)
		.replace('DD', day)
		.replace('hh', hour)
		.replace('mm', minute)
		.replace('ss', second)
}

export async function wxLogin() {
	const {
		result: userInfo
	} = await wx.cloud.callFunction({
		name: 'getUserInfo'
	})
	const userCollection = wx.cloud.database().collection('jeilong_user')
	const {
		data: list
	} = await userCollection.where({
		openid: userInfo.openid
	}).get()
	const data = {
		openid: userInfo.openid
	}
	let result
	if (list.length === 0) {
		data.nickName = null
		data.phone = null
		const {
			_id
		} = await userCollection.add({
			data: {
				...data,
				createTime: wx.cloud.database().serverDate(),
			}
		})
		result = {
			...data,
			_id,
			createTime: new Date()
		}
	} else {
		result = list[0]
	}
	uni.setStorageSync('userInfo', result)
	return result
}